package com.nba.common.utils;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

public class FileUtils {
    protected static Logger logger = Logger.getLogger(FileUtils.class);
    
    public static int[] calcImgWH(int width, int height, int size){
        float w=0, h=0;
        if(width <= size || height <= size){//判断图片本身大小不比缩略图小
            w = width;
            h = height;
        }else{
            if(width > height){//如果是宽屏图片，则把高度限制，宽度计算。
                h = size;
                w = size * ((float)width/(float)height);
            }else{
                w = size;
                h = size * ((float)height/(float)width);
            }
        }
        int[] i = new int[2];
        i[0] = (int)w;
        i[1]= (int)h;
        return i;
    }
    public static Map<String,Object> saveImg(@RequestParam MultipartFile file, HttpServletRequest request, boolean thumbnailFlag) {
        Map<String,Object> map = new HashMap<String,Object>();
        OutputStream fos = null;
        InputStream ins = null;
        try {
            if ((file != null) && (!file.isEmpty())) {
                String savepath = request.getSession()
                        .getServletContext()
                        .getRealPath(Environment.IMG_SEC_PATH);// + File.separator
                File createFile = new File(savepath);
                if (!createFile.exists()) {
                    createFile.mkdirs();
                }
                String fileName = file.getOriginalFilename();
                String fileext = "";
                if(fileName.lastIndexOf(".")!=-1){
                    fileext=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                }
                String saveName = new UUID().generate().toString();
                String fullPath = savepath + File.separator + saveName+ "."+fileext;
                fos = new FileOutputStream(fullPath);
                ins = file.getInputStream();
                //图片大小
                BufferedImage bi=ImageIO.read(file.getInputStream()); 
                int imgWidth = bi.getWidth();
                int imgHeight = bi.getHeight();
                map.put("width", imgWidth);
                map.put("height", imgHeight);
                
                byte[] buffer = new byte[2 * 1024 * 1024];
                int length = 0;
                while (-1 != (length = ins.read(buffer))) {
                    fos.write(buffer, 0, length);
                }
                try {
                    fos.close();
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(thumbnailFlag){//缩略图
                    String ctxPath = CommonUtils.getFullContextPath(request)+Environment.IMG_SEC_PATH;
                    int[] wh = calcImgWH(imgWidth, imgHeight, Environment.IMG_SMALL_SIZE);
                    ImageUtil.createSmall(ctxPath, savepath, saveName, Environment.IMG_SMALL_FLODER, fileext, wh[0], wh[1]);
                    wh = calcImgWH(imgWidth, imgHeight, Environment.IMG_MIDDLE_SIZE);
                    ImageUtil.createSmall(ctxPath, savepath, saveName, Environment.IMG_MIDDLE_FLODER, fileext, wh[0], wh[1]);
                    wh = calcImgWH(imgWidth, imgHeight, Environment.IMG_BIG_SIZE);
                    ImageUtil.createSmall(ctxPath, savepath, saveName, Environment.IMG_BIG_FLODER, fileext, wh[0], wh[1]);
                }
                map.put("success", Integer.valueOf(1));
                map.put("fileName", saveName);
                map.put("fileExt", fileext);
                return map;
            } else {
                map.put("success", Integer.valueOf(0));
                map.put("fileName", "");
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", Integer.valueOf(0));
            map.put("fileName", "");
            return map;
        }
    }
    
    public static Map<String,Object> saveFile(@RequestParam MultipartFile file, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        OutputStream fos = null;
        InputStream ins = null;
        try {
            if ((file != null) && (!file.isEmpty())) {
                String savepath = request.getSession()
                        .getServletContext()
                        .getRealPath(Environment.FILE_SEC_PATH);// + File.separator
                File createFile = new File(savepath);
                if (!createFile.exists()) {
                    createFile.mkdirs();
                }
                String fileName = file.getOriginalFilename();
                String fileext = "";
                if(fileName.lastIndexOf(".")!=-1){
                    fileext=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
                }
                String saveName = new UUID().generate().toString();
                String fullPath = savepath + File.separator + saveName+ "."+fileext;
                fos = new FileOutputStream(fullPath);
                ins = file.getInputStream();
                
                byte[] buffer = new byte[2 * 1024 * 1024];
                int length = 0;
                while (-1 != (length = ins.read(buffer))) {
                    fos.write(buffer, 0, length);
                }
                try {
                    fos.close();
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                map.put("success", Integer.valueOf(1));
                map.put("fileName", saveName);
                map.put("fileExt", fileext);
                return map;
            } else {
                map.put("success", Integer.valueOf(0));
                map.put("fileName", "");
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", Integer.valueOf(0));
            map.put("fileName", "");
            return map;
        }
    }
    public static String getFileSizeFormat(long fsize){
        String sss = "";
        if(fsize < 1*1024*1024){
            double dbe = fsize/1024;
            DecimalFormat df=new DecimalFormat("#.00");
            sss = df.format(dbe) + " KB";
        }else{
            double db=fsize;
            double dbe = db/1024/1024;
            DecimalFormat df=new DecimalFormat("#.00");
            sss = df.format(dbe)+ " MB";
        }
        return sss;
    }
}
